package io.github.zeleven.mua.fraction;

import io.github.zeleven.mua.BaseEditorFragment;
import io.github.zeleven.mua.ResourceTable;
import io.github.zeleven.mua.bean.EditCallback;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * PreviewFragment
 *
 * @since 2021-05-11
 */
public class PreviewFragment extends BaseEditorFragment {
    private static final int INT = 0x001234;
    private static final int TWO = 2;
    private WebView mWebView;
    private Image back;
    private Image pencil;
    private EditCallback callback;

    /**
     * PreviewFragment
     *
     * @param slice
     * @param callback
     */
    public PreviewFragment(AbilitySlice slice, EditCallback callback) {
        this.callback = callback;
    }

    @Override
    public int getLayoutId() {
        return ResourceTable.Layout_fragment_preview;
    }

    /**
     * setValue
     *
     * @param value
     */
    public void setValue(String value) {
        String content = value.replace("\n", "\\n").replace("\"", "\\\"")
                .replace("'", "\\'");
        mWebView.setWebAgent(new WebAgent() {
            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                webView.executeJs("parseMarkdown('" + content + "')", null);
            }
        });
    }

    @Override
    public void initView(Component view) {
        mWebView = (WebView) view.findComponentById(ResourceTable.Id_preview_webview);
        back = (Image) view.findComponentById(ResourceTable.Id_preview_back);
        pencil = (Image) view.findComponentById(ResourceTable.Id_preview_edit);
        configWebView();

        pencil.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                callback.preview(TWO, "");
            }
        });

        back.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                callback.preview(TWO, "");
            }
        });

        mWebView.getWebConfig().setDataAbilityPermit(true);

        // 加载资源文件 resources/rawfile/example.html
        mWebView.load("dataability://com.example.dataability/rawfile/markdown.html");
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * configWebView
     *
     */
    public void configWebView() {
        mWebView.getWebConfig().setJavaScriptPermit(true);
    }
}